import { apiClient } from './client'
import {
  AdminStats,
  User,
  Plugin,
  AuditLog,
  SecurityScan,
  UserFilters,
  PluginFilters,
  ApiResponse
} from '@/types/api'

export class AdminService {
  // Dashboard stats
  async getStats(): Promise<ApiResponse<AdminStats>> {
    return apiClient.get('/admin/stats')
  }

  // User management
  async getUsers(filters: UserFilters = {}): Promise<ApiResponse<{ users: User[] }>> {
    const params = new URLSearchParams()
    
    Object.entries(filters).forEach(([key, value]) => {
      if (value !== undefined && value !== null && value !== '') {
        params.append(key, value.toString())
      }
    })

    return apiClient.get(`/admin/users?${params.toString()}`)
  }

  async getUserById(id: string): Promise<ApiResponse<{ user: User }>> {
    return apiClient.get(`/admin/users/${id}`)
  }

  async suspendUser(id: string, reason: string): Promise<ApiResponse> {
    return apiClient.post(`/admin/users/${id}/suspend`, { reason })
  }

  async unsuspendUser(id: string): Promise<ApiResponse> {
    return apiClient.post(`/admin/users/${id}/unsuspend`)
  }

  async deleteUser(id: string): Promise<ApiResponse> {
    return apiClient.delete(`/admin/users/${id}`)
  }

  async updateUserRole(id: string, role: string): Promise<ApiResponse> {
    return apiClient.patch(`/admin/users/${id}/role`, { role })
  }

  // Plugin management
  async getAllPlugins(filters: PluginFilters = {}): Promise<ApiResponse<{ plugins: Plugin[] }>> {
    const params = new URLSearchParams()
    
    Object.entries(filters).forEach(([key, value]) => {
      if (value !== undefined && value !== null && value !== '') {
        if (Array.isArray(value)) {
          value.forEach(v => params.append(key, v))
        } else {
          params.append(key, value.toString())
        }
      }
    })

    return apiClient.get(`/admin/plugins?${params.toString()}`)
  }

  async getPendingPlugins(): Promise<ApiResponse<{ plugins: Plugin[] }>> {
    return apiClient.get('/admin/plugins/pending')
  }

  async approvePlugin(id: string, reason?: string): Promise<ApiResponse> {
    return apiClient.post(`/admin/plugins/${id}/approve`, { reason })
  }

  async rejectPlugin(id: string, reason: string): Promise<ApiResponse> {
    return apiClient.post(`/admin/plugins/${id}/reject`, { reason })
  }

  async suspendPlugin(id: string, reason: string): Promise<ApiResponse> {
    return apiClient.post(`/admin/plugins/${id}/suspend`, { reason })
  }

  async unsuspendPlugin(id: string): Promise<ApiResponse> {
    return apiClient.post(`/admin/plugins/${id}/unsuspend`)
  }

  async deletePlugin(id: string): Promise<ApiResponse> {
    return apiClient.delete(`/admin/plugins/${id}`)
  }

  async featurePlugin(id: string): Promise<ApiResponse> {
    return apiClient.post(`/admin/plugins/${id}/feature`)
  }

  async unfeaturePlugin(id: string): Promise<ApiResponse> {
    return apiClient.delete(`/admin/plugins/${id}/feature`)
  }

  // Security management
  async getSecurityStats(): Promise<ApiResponse<any>> {
    return apiClient.get('/advanced-security/stats')
  }

  async getSecurityScans(filters: any = {}): Promise<ApiResponse<{ scans: SecurityScan[] }>> {
    const params = new URLSearchParams()
    
    Object.entries(filters).forEach(([key, value]) => {
      if (value !== undefined && value !== null && value !== '') {
        params.append(key, value.toString())
      }
    })

    return apiClient.get(`/admin/security/scans?${params.toString()}`)
  }

  async triggerSecurityScan(versionId: string, scanType?: string): Promise<ApiResponse> {
    const url = scanType 
      ? `/advanced-security/scan/${scanType}`
      : '/advanced-security/scan/comprehensive'
    return apiClient.post(url, { versionId })
  }

  async getSecurityReport(versionId: string): Promise<ApiResponse<any>> {
    return apiClient.get(`/advanced-security/reports/security/${versionId}`)
  }

  async getThreatIntelligence(): Promise<ApiResponse<any>> {
    return apiClient.get('/advanced-security/threat-intelligence')
  }

  // Signature management
  async getSignatureCertificates(): Promise<ApiResponse<any>> {
    return apiClient.get('/signature/certificates')
  }

  async generateSignatureCertificate(issuer: string): Promise<ApiResponse<any>> {
    return apiClient.post('/signature/certificates/generate', { issuer })
  }

  async revokeCertificate(keyId: string, reason: string): Promise<ApiResponse> {
    return apiClient.post(`/signature/certificates/${keyId}/revoke`, { keyId, reason })
  }

  async signPlugin(versionId: string, keyId?: string): Promise<ApiResponse<any>> {
    return apiClient.post('/signature/sign', { versionId, keyId })
  }

  async verifySignature(versionId: string): Promise<ApiResponse<any>> {
    return apiClient.get(`/signature/verify/${versionId}`)
  }

  // Audit logs
  async getAuditLogs(filters: any = {}): Promise<ApiResponse<{ logs: AuditLog[] }>> {
    const params = new URLSearchParams()
    
    Object.entries(filters).forEach(([key, value]) => {
      if (value !== undefined && value !== null && value !== '') {
        params.append(key, value.toString())
      }
    })

    return apiClient.get(`/admin/audit-logs?${params.toString()}`)
  }

  // System management
  async getSystemHealth(): Promise<ApiResponse<any>> {
    return apiClient.get('/admin/system/health')
  }

  async getSystemMetrics(): Promise<ApiResponse<any>> {
    return apiClient.get('/admin/system/metrics')
  }

  async clearCache(): Promise<ApiResponse> {
    return apiClient.post('/admin/system/clear-cache')
  }

  async exportData(type: string, filters?: any): Promise<ApiResponse<any>> {
    return apiClient.post('/admin/export', { type, filters })
  }

  // Reports
  async generateReport(type: string, period: string, filters?: any): Promise<ApiResponse<any>> {
    return apiClient.post('/admin/reports/generate', { type, period, filters })
  }

  async getReports(): Promise<ApiResponse<any>> {
    return apiClient.get('/admin/reports')
  }

  async downloadReport(reportId: string): Promise<void> {
    return apiClient.download(`/admin/reports/${reportId}/download`)
  }

  // Settings
  async getSettings(): Promise<ApiResponse<any>> {
    return apiClient.get('/admin/settings')
  }

  async updateSettings(settings: any): Promise<ApiResponse<any>> {
    return apiClient.patch('/admin/settings', settings)
  }

  // Notifications
  async sendNotification(data: {
    type: 'email' | 'system'
    recipients: string[]
    subject: string
    message: string
  }): Promise<ApiResponse> {
    return apiClient.post('/admin/notifications/send', data)
  }

  async getNotificationTemplates(): Promise<ApiResponse<any>> {
    return apiClient.get('/admin/notifications/templates')
  }

  async createNotificationTemplate(template: any): Promise<ApiResponse<any>> {
    return apiClient.post('/admin/notifications/templates', template)
  }
}

export const adminService = new AdminService()
